package com.jd.risk.bankorder.util.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.wangyin.commons.util.Logger;
import com.wangyin.commons.util.LoggerFactory;
import com.wangyin.hsp.client.HSPClient;
import com.wangyin.hsp.client.HSPConfig;
import com.wangyin.hsp.client.NetFile;
import com.wangyin.hsp.client.model.result.SaveResult;

@Service(value="hdfsHelper")
public class HdfsHelper{
	
	private static Logger logger =  LoggerFactory.getLogger(HdfsHelper.class);
	
	@Value("${hdfs.hsp.connectString}")
	private String connectString;
	
	@Value("${hdfs.hsp.applicationID}")
	private String applicationId;
	
	@Value("${hdfs.hsp.audit.applicationPwd}")
	private String applicationPw;
	
	@Value("${hdfs.hsp.httpServerUrl}")
	private String httpServerUrl;
	
	/**
	 * HDFS byte[]限制在1M之内
	 * 
	 * @param uniqueFileName
	 * @param fileBytes
	 * @return result .getRetcode()   1 表示上传成功，小于等于0 表示失败
	   result .getFid() 上传成功以后 返回fid
	 */
	public SaveResult upload(byte[] fileBytes ) {
		HSPConfig config = new HSPConfig(connectString, Integer.valueOf(applicationId), applicationPw);
		config.setHttpServerUrl(httpServerUrl);
		HSPClient client = new HSPClient(config);
		SaveResult result = new SaveResult();
		try {
			result = client.save(fileBytes);
			return result;
		}
		catch (Exception e) 
		{
			logger.error(e);
			return result;
		} finally {	
			try {
				if (client != null) {
					client.close();
					//不再需要时，请调用close释放网络连接等资源。
				}
			} catch (InterruptedException e) {
				logger.error(e);
			}
		}

	}

	/**
	 * 
	 * 获取文件的byte[]  限制在1M之内
	 * 
	 * @param origFileName
	 * @param output
	 * @return
	 */
	public byte[] download(String fid){
		HSPConfig config = new HSPConfig(connectString, Integer.valueOf(applicationId), applicationPw);
		config.setHttpServerUrl("http://172.25.47.95");
		NetFile  netfile = new NetFile (config);
		byte buf[]=null;  //最大1M，
		if(netfile.Open(fid)) {   
			try { 
				int readlen=0;
				buf = new byte[1024*1024];
				do{    
				 //大文件需要分多次读，一次最多读1M
				int offset=0 ;        // buf的偏移量
				int len= buf.length;  //要读出的长度
					readlen = netfile.Read(buf,offset,len); //对读出的buf处理…
				   
				}  while(readlen>0 && !netfile.IsEof());
			}catch (Exception e){
				logger.error(e.getMessage());
				//具体异常类型请参考接口说明，并针对不同类型的异常做不同的处理。
			} finally{
				logger.info("HSF获取 fid:"+fid+" 结束");
			}
		}
		return buf;
	}
}